package com.niit.agricstore.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageInfo;
import com.niit.agricstore.entity.Token;
import com.niit.agricstore.entity.User;
//import com.niit.agricstore.service.RedisService;
import com.niit.agricstore.entity.vo.UserRegisterVo;
import com.niit.agricstore.service.RedisService;
import com.niit.agricstore.service.UserService;
import com.niit.agricstore.util.JwtUtils;
import com.niit.agricstore.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.*;

@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    RedisService redisService;
    private  UserService userService;
    @Autowired
    public void setUserService(UserService userService) {

        this.userService = userService;
    }
//    @Autowired
//    RedisService redisService;
    @GetMapping("/all")
    public Result findUserAll(){
        List<User> userList= userService.findAllUsers();
        return Result.success(userList);
    }
    @GetMapping("/allByPage")
    public Result getPage(@RequestParam("pageNum")int pageNum, @RequestParam("pageSize")int pageSize){
        PageInfo<User> list = userService.findUserAllByPage(pageNum,pageSize);
        return Result.success(list);
    }
    @GetMapping("/nameByPage/{pageNum}/{pageSize}/{name}")
    public Result getNameByPage(@PathVariable("pageNum")int pageNum,
                                @PathVariable("pageSize")int pageSize,
                                @PathVariable("name") String name){
        PageInfo<User> list = userService.findUserNameByPage(pageNum,pageSize,name);
        return Result.success(list);
    }
    @GetMapping("/IdByPage/{pageNum}/{pageSize}/{id}")
    public Result geIdByPage(@PathVariable("pageNum")int pageNum,
                                @PathVariable("pageSize")int pageSize,
                                @PathVariable("id")Long id){
        PageInfo<User> list = userService.findUserIdByPage(pageNum,pageSize,id);
        return Result.success(list);
    }
    @GetMapping("/phoneByPage/{pageNum}/{pageSize}/{phone}")
    public Result geIdByPage(@PathVariable("pageNum")int pageNum,
                             @PathVariable("pageSize")int pageSize,
                             @PathVariable("phone")String phone){
        PageInfo<User> list = userService.findUserPhoneByPage(pageNum,pageSize,phone);
        return Result.success(list);
    }
    @PostMapping("/login/{username}/{password}")
    public Result login(@PathVariable String username,@PathVariable String password) {
        if (username.equals("")||username==null) return Result.error("205","账号不能为空");
        if (password.equals("")||password==null) return Result.error("206","密码不能为空");
        User user1 = userService.loginCheck(username, password);
        if (user1 == null) {//没有查询到数据，代表没有此账号
            return Result.error("207","账号密码不正确，请重试");
        } else {
            if(user1.getUserIsAdmin()==1){
                return Result.error("207","抱歉，您没有登录本端的权限");
            }
//            if (redisService.get(user1.getUserName())==null){
                Result result = Result.success(userService.loginCheck(username, password));
                String tokenStr = JwtUtils.generateToken(String.valueOf(user1.getUserId()));
                Token token = new Token();
                token.setAuthorization(tokenStr);
                token.setObj(user1);
                result.setData(token);
                System.out.println("进入访问====");
               redisService.incr("count",1);    //没访问一次，那么访问量就加1
               System.out.println(redisService.get("count"));
//                redisService.set(username,token,1800);
                return result;
//            }else {
//                return  Result.error("500","该用户已在其他设备登陆");
//        }
    }
    }
    @GetMapping("/count")
    public Result getCount(){
        return Result.success(redisService.get("count"));
    }
    @PostMapping("/login/admin/{username}/{password}")
    public Result loginAdmin(@PathVariable String username,@PathVariable String password) {
        if (username==null) return Result.error("205","账号不能为空");
        if (password==null) return Result.error("206","密码不能为空");
        User user1 = userService.loginCheck(username, password);
        if (user1 == null) {//没有查询到数据，代表没有此账号
            return Result.error("207","账号密码不正确，请重试");
        } else {
            if(user1.getUserIsAdmin()!=1){
                return Result.error("207","抱歉，您没有登录管理端的权限");
            }
//            if (redisService.get(user1.getUserName())==null){
            Result result = Result.success(userService.loginCheck(username, password));
            String tokenStr = JwtUtils.generateToken(String.valueOf(user1.getUserId()));
            Token token = new Token();
            token.setAuthorization(tokenStr);
            token.setObj(user1);
            result.setData(token);
//                redisService.set(username,token,1800);
            return result;
//            }else {
//                return  Result.error("500","该用户已在其他设备登陆");
//        }
        }
    }
    //用户注册
    @PostMapping(path = "/register",consumes = MediaType.APPLICATION_JSON_VALUE)
    public Result register(@RequestBody UserRegisterVo userRegisterVo) {
        User user = new User();
        user.setUserPassword(userRegisterVo.getPassword());
        user.setUserName(userRegisterVo.getUsername());
        user.setUserPhone(userRegisterVo.getPhone());
        user.setUserIsAdmin(0);
        user.setUserIsDelete(0);
        user.setUserCreateTime(new Date());
        user.setUserLoginTime(new Date());
        String success = userService.userRegister(user);
        return Result.success(success);
    }
    //修改用户密码
    @PutMapping("updatePassword/{id}/{newpass}")
    public int updatePassword(@PathVariable("id")Long id,@PathVariable("newpass")String newpass){
        return userService.updatePassword(id, newpass);
    }
    //删除用户，实际上是修改isDeleted字段
    @PutMapping("delete/{id}")
    public int deleteUser(@PathVariable("id")Long id){
        return userService.deleteUser(id);
    }
    //修改手机号
    @PutMapping("updatePhone/{id}/{phone}")
    public int updatePhone(@PathVariable("id")Long id,@PathVariable("phone")String phone){
        return userService.updatePhone(id, phone);
    }

    @PostMapping("/updateAvatar")
    public Result updateAvatar(
//            @RequestParam("id")Long id,
                               @RequestParam("file")MultipartFile avatar) throws IOException {
        if(!avatar.isEmpty()) {
            System.out.println("文件非空");
            String fileName = avatar.getOriginalFilename();
            String suffixName = "/home";
            //设置上传文件的保存地址目录
            String dirpath="D:/upload";
            System.out.println(dirpath);
            File parentFilePath=new File(dirpath);
            //如果保存文件不存在就先创建目录
            if(!parentFilePath.exists()) {
                parentFilePath.mkdir();
            }
            String fileNewName = UUID.randomUUID() + fileName;

            File newFile = new File(parentFilePath, fileNewName);
            System.out.println(newFile.getPath());
            avatar.transferTo(newFile);
            System.out.println(newFile.getPath());
            return Result.success(newFile);
        }
        System.out.println("空文件"+avatar);
        return Result.error("660","文件为空");
    }
   //获取当前用户信息
    @GetMapping("/me/{id}")
    public Result<User> getCurrentUserInfo(@PathVariable("id")Long id) {
        User user = userService.getCurrentUser(id);
        return Result.success(user);}

//    @GetMapping("/getPageById")
//    public Result<User> findUserId(@RequestParam("id")Long id,@) {
//        User user = userService.findUserIdByPage()
//        return Result.success(user);}
    //修改头像请求，暂时设定存储路径拼接到本地。
//    @RequestMapping("/uploadHeadPic")
//    public Result uploadHeadPic(@RequestParam("file") MultipartFile file) throws IOException {
//        // 项目路径
//        File projectPath = new File(ResourceUtils.getURL("classpath:").getPath());
//        System.out.println("projectPath="+projectPath);
//        // 绝对路径=项目路径+自定义路径
//        File upload = new File(projectPath.getAbsolutePath(), "static/user/");
//        if (!upload.exists())
//            upload.mkdirs();
//        Result result=null;
//        if (file.isEmpty()) {
//            result=Result.error("202","上传失败");
//        }
//        else{
//            //获取文件名称
//            String fileName=file.getOriginalFilename();
//            System.out.println("dest="+upload.getAbsolutePath()+"\\"+fileName);
//            File dest=new File(upload.getAbsolutePath()+"\\"+fileName);
//            //文件IO
//            file.transferTo(dest);
//            result=Result.success();
//            result.setCode("0");
//            result.setMsg("上传成功");
//            Map<String,String> map=new HashMap<>();
//            map.put("src",fileName);
//            result.setData(map);
//        }
//
//        return result;
//    }

}
